from typing import Optional, Dict, Any, List
from datetime import datetime
from pydantic import BaseModel, validator


class ShipmentBase(BaseModel):
    """货物追踪基础模式"""
    number_no: Optional[str] = None
    pickup_warehouse: Optional[str] = None
    delivery_warehouse: Optional[str] = None
    mac_id: Optional[str] = None
    route_data: Optional[Dict[str, Any]] = None
    pickup_warehouse_coordinates: Optional[str] = None
    delivery_warehouse_coordinates: Optional[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    status: Optional[int] = 0
    execution_info: Optional[str] = None


class ShipmentCreate(ShipmentBase):
    """货物追踪创建模式"""
    number_no: str
    pickup_warehouse: str
    delivery_warehouse: str
    mac_id: str

    @validator('number_no', 'pickup_warehouse', 'delivery_warehouse', 'mac_id')
    def fields_not_empty(cls, v, values, **kwargs):
        if not v or not v.strip():
            field_name = kwargs['field'].name
            raise ValueError(f'{field_name}不能为空')
        return v.strip()


class ShipmentUpdate(ShipmentBase):
    """货物追踪更新模式"""
    version: int  # 用于乐观锁控制


class ShipmentInDBBase(ShipmentBase):
    """数据库中的货物追踪模式基类"""
    id: int
    version: int
    create_time: Optional[datetime] = None
    update_time: Optional[datetime] = None
    create_by: Optional[str] = None
    update_by: Optional[str] = None

    class Config:
        orm_mode = True


class Shipment(ShipmentInDBBase):
    """返回给客户端的货物追踪模式"""
    pass


class ShipmentInDB(ShipmentInDBBase):
    """数据库中的货物追踪模式，完整信息"""
    pass


class RoutePoint(BaseModel):
    """路线点位置"""
    lat: float  # 纬度
    lng: float  # 经度
    timestamp: Optional[int] = None  # 时间戳
    speed: Optional[float] = None  # 速度
    altitude: Optional[float] = None  # 海拔
    time: Optional[str] = None  # 时间字符串
    mileage: Optional[float] = None  # 里程


class ShipmentRoute(BaseModel):
    """货物路线数据"""
    shipment_id: int
    points: List[RoutePoint]